const topicModel = require('../models/topic.js')

exports.list = async (req, res, next) => {
	try {
		const {topics,count} = await topicModel.getTopics(req.query)
		res.status(200).json({
			topics,
			count
		})
	} catch(err) {
		next(err)
	}
}

exports.one = async (req, res, next) => {
	try {
		const {id} = req.params
		const topic = await topicModel.getTopic(id)
		res.status(200).json(topic)
	} catch(err) {
		next(err)
	}
}

exports.create = async (req, res, next) => {
	try {
		let body = req.body
		body.user_id = req.session.user.id
		const id = await topicModel.addTopic(body)
		const topic = await topicModel.getTopic(id)
		res.status(201).json(topic)
	} catch(err) {
		next(err)
	}
}

exports.update = async (req, res, next) => {
	try {
		let body = req.body
		const {id} = req.params
		body.id = id
		await topicModel.editTopic(body)
		const updateTopic = await topicModel.getTopic(id)
		res.status(201).json(updateTopic)
	} catch(err) {
		next(err)
	}
}

exports.delete = async (req, res, next) => {
	try {
		const {id} = req.params
		await topicModel.deleteById(id)
		res.status(201).json({})
	} catch(err) {
		next(err)
	}
}
